#include <stdio.h>  
#include <stdlib.h>  
  
// 定义二叉树节点结构体  
struct TreeNode {  
    int val;  
    struct TreeNode *left;  
    struct TreeNode *right;  
};  
  
// 创建新节点  
struct TreeNode* createNode(int val) {  
    struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));  
    node->val = val;  
    node->left = NULL;  
    node->right = NULL;  
    return node;  
}  
  
// 插入节点  
struct TreeNode* insertNode(struct TreeNode* root, int val) {  
    if (root == NULL) {  
        return createNode(val);  
    }  
    if (val < root->val) {  
        root->left = insertNode(root->left, val);  
    } else if (val > root->val) {  
        root->right = insertNode(root->right, val);  
    }  
    return root;  
}  
  
// 查找节点  
struct TreeNode* searchNode(struct TreeNode* root, int val) {  
    if (root == NULL || root->val == val) {  
        return root;  
    }  
    if (val < root->val) {  
        return searchNode(root->left, val);  
    } else {  
        return searchNode(root->right, val);  
    }  
}  
  
// 删除节点  
struct TreeNode* deleteNode(struct TreeNode* root, int val) {  
    if (root == NULL) {  
        return root;  
    }  
    if (val < root->val) {  
        root->left = deleteNode(root->left, val);  
    } else if (val > root->val) {  
        root->right = deleteNode(root->right, val);  
    } else {  
        if (root->left == NULL) {  
            struct TreeNode* temp = root->right;  
            free(root);  
            return temp;  
        } else if (root->right == NULL) {  
            struct TreeNode* temp = root->left;  
            free(root);  
            return temp;  
        } else {  
            struct TreeNode* minNode = findMinNode(root->right);  
            root->val = minNode->val;  
            root->right = deleteNode(root->right, minNode->val);  
        }  
    }  
    return root;  
}  
  
// 查找最小节点（辅助函数）  
struct TreeNode* findMinNode(struct TreeNode* node) {  
    while (node->left != NULL) {  
        node = node->left;  
    }  
    return node;  
}